package com.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.bean.User;
import com.wms.config.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.wms.service.WarehouseService;
import com.wms.bean.Warehouse;
import java.util.List;

@RestController
@RequestMapping("warehouse")
@CrossOrigin
public class WarehouseController {
 @Autowired
    WarehouseService warehouseService;

 @GetMapping("/list")
    public Result getlist() {
        List<Warehouse> list = warehouseService.list();
        return Result.success(list);
    }
    @PostMapping("/add")
    public Result add(@RequestBody Warehouse warehouse) {
       warehouseService.save(warehouse);
        Warehouse savedWarehouse = warehouseService.getById(warehouse.getWid());
        return Result.success("保存成功", savedWarehouse);
    }
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") int id) {
        boolean b = warehouseService.removeById(id);
        if (b) {
            return Result.success("删除成功");
        } else {
            return Result.fail(201, "删除失败");
        }
    }
    @PutMapping("/update")
    public Result update(@RequestBody Warehouse warehouse) {
        boolean b = warehouseService.updateById(warehouse);
        if (b) {
            Warehouse updatedWarehouse = warehouseService.getById(warehouse.getWid());
            return Result.success("修改成功", updatedWarehouse);
        } else {
            return Result.fail(201, "修改失败");
        }
    }
    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchtext") String searchtext) {
        IPage<Warehouse> result;

        if (searchtext == null || searchtext.isEmpty()) {
            result = warehouseService.page(page);
        } else {
            QueryWrapper<Warehouse> wrapper = new QueryWrapper<Warehouse>();
            wrapper.like("wid", searchtext)
                    .or().like("wname", searchtext);

            result = warehouseService.page(page, wrapper); // ✅ 使用 wrapper 查询
        }

        return Result.success(result);
    }

}